package com.scan.bus.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scan.bus.MainActivity;
import com.scan.bus.MyApp;
import com.scan.bus.bean.EmptyEntity;
import com.scan.bus.event.EventBusMessage;
import com.scan.bus.event.ToastBusMessage;
import com.scan.bus.util.Common;
import com.scan.bus.util.LogUtil;
import com.scan.bus.util.SharedPrefUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;

public class PushBusReceiver extends JPushMessageReceiver {

    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        LogUtil.httpLogW("customMessage:"+customMessage.message);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            EventBusMessage eventBusMessage = objectMapper.readValue(customMessage.message,EventBusMessage.class);
            EventBus.getDefault().post(eventBusMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage message) {
        try{
            LogUtil.httpLogW("NotificationMessage:"+message.toString());
        }catch (Throwable throwable){

        }
    }

    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
        super.onAliasOperatorResult(context, jPushMessage);
        LogUtil.httpLogW("别名结果："+jPushMessage.getAlias()+" 状态码："+jPushMessage.getErrorCode());
        if(jPushMessage!=null) {
          String uuid = SharedPrefUtil.getCacheSharedPrf("X-Device-ID", "");
            if (jPushMessage.getAlias() != null && !jPushMessage.getAlias().equals("") &&uuid.equals(jPushMessage.getAlias())){
                if(jPushMessage.getErrorCode()==0) {
                    MyApp.isSuccessResgiter = true;
                }
            }
        }
    }

    @Override
    public void onRegister(Context context, String s) {
        super.onRegister(context, s);
    }

    @Override
    public void onConnected(Context context, boolean b) {
        super.onConnected(context, b);
        LogUtil.httpLogW("别名结果长链接状态："+b);
//        EventBus.getDefault().post(new ToastBusMessage("长链接状态："+b));
    }

}
